//
//  TL_UtilsHelper.m
//  WXDating
//
//  Created by Andrew on 2017/8/13.
//  Copyright © 2017年 Andrew. All rights reserved.
//

#import "TL_UtilsHelper.h"
#import "UUID.h"
#import <sys/utsname.h>
#import "CommonCrypto/CommonDigest.h"
#import <CommonCrypto/CommonCrypto.h>

//#import "TL_ProductionCollectionManager.h"
#import "TL_WebViewViewController.h"
#import "AppDelegate.h"
//#import "TL_FeedbackSubViewController.h"

//#import "TLChacheUtils.h"

static NSString * const kCGCache_searchHistory  = @"kCGCache_searchHistory";

@implementation TL_UtilsHelper

+ (NSInteger)timestamp {
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970] * 1000;
    return currentTime;
}

#pragma mark - 设备信息
+ (NSString *)getUDID
{
    return [UUID getUUID];
}

+ (NSString *)getSystemVersion
{
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)getCurrentDeviceModel
{
    struct utsname systemInfo;
    uname(&systemInfo);
    
    return [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
}

+ (long long)getFileSize:(NSString *)filePath
{
    long long ret = 0;
    
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
    ret = [fileSizeNumber longLongValue];
    
    return ret;
}

#pragma mark -  工具类

/// 根据属性名创建对应的set方法。
/// @param name 属性名
+ (SEL)createSetterWithPropertyName:(NSString *)name {
    if (!name || name.length == 0) return nil;
    
    NSString *firstStirng = [name substringToIndex:1];
    NSString *lastString = [name substringFromIndex:1];
    name = [firstStirng.capitalizedString stringByAppendingString:lastString];
    name = [NSString stringWithFormat:@"set%@:", name];
    
    return NSSelectorFromString(name);
}

+ (void)synchronizationRack
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 同步小说
        [self synchronizationRackProductionWithProduction_id:0 productionType:TL_ProductionTypeBook complete:nil];
        
        // 同步漫画
        [self synchronizationRackProductionWithProduction_id:0 productionType:TL_ProductionTypeComic complete:nil];
    });
}

+ (NSURLSessionDataTask *)synchronizationRackProductionWithProduction_id:(NSInteger)production_id productionType:(TL_ProductionType)productionType complete:(void(^ _Nullable)(BOOL status))complete
{
    return [self synchronizationRackProductionWithProduction_id:production_id productionType:productionType complete:complete isCover:NO];
}

+ (NSURLSessionDataTask *)synchronizationRackProductionWithProduction_id:(NSInteger)production_id productionType:(TL_ProductionType)productionType complete:(void(^ _Nullable)(BOOL status))complete isCover:(BOOL)isCover {
//    if (!TL_UserInfoManager.isLogin) {
//        return nil;
//    }
    
    NSString *url = @"";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
//    switch (productionType) {
//        case TL_ProductionTypeBook:
//            url = Book_Add_Collect;
//            [parameters setObject:@"book_id" forKey:@"key"];
//            break;
//        case TL_ProductionTypeComic:
//            url = Comic_Collect_Add;
//            [parameters setObject:@"comic_id" forKey:@"key"];
//            break;
//        default:
//            break;
//    }
//    
//    // 添加作品
//    if (production_id > 0) {
//        [parameters setObject:[TL_UtilsHelper formatStringWithInteger:production_id] forKey:[parameters objectForKey:@"key"]];
//        
//     // 同步作品
//    } else {
//        
//        NSArray <TL_ProductionModel *> *t_arr = [[TL_ProductionCollectionManager shareManagerWithProductionType:productionType] getAllCollection];
//        
//        NSMutableArray *productionArray = [NSMutableArray array];
//        for (TL_ProductionModel *t_productionModel in t_arr) {
//            [productionArray addObject:[TL_UtilsHelper formatStringWithInteger:t_productionModel.production_id]];
//        }
//        
//        [parameters setObject:[productionArray componentsJoinedByString:@","] forKey:[parameters objectForKey:@"key"]];
//        [parameters setObject:@"1" forKey:@"auto_add"];
//        [parameters setObject:isCover ? @"1" : @"0" forKey:@"is_cover"];
//    }
    
    NSString *urlStr = [APIURLManager collectBook];
    NSDictionary *param = @{
        @"worksId":@(production_id)
    };
    
    return [APIManager sendPostRequest:urlStr parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        !complete ?: complete(success);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !complete ?: complete(NO);
    }];
    
}

+ (BOOL)isInSafetyPeriod
{
#if WX_Enable_Magic
    if ([TL_SystemInfoManager.magicStatus isEqualToString:@"0"]) {
        return NO;
    } else if ([TL_SystemInfoManager.magicStatus isEqualToString:@"1"]) {
        return YES;
    }
    
    NSDateFormatter *date = [[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 提交审核日期
    NSDate *sd = [date dateFromString:Submission_Date];
    
    // 预计审核成功日期
    NSDate *ead = [[NSDate date] initWithTimeInterval:24 * 3600 * DELAY_DAYS sinceDate:sd];
    
    // 预计日期 - 当前日期
    NSTimeInterval si = [ead timeIntervalSince1970] * 1;
    NSTimeInterval ei = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    NSTimeInterval value = si - ei;
    
    // 天
    int day = (int)value / (24 * 3600);
    
    if (day > 0) { // 在审核期
        return YES;
    } else {// 非审核期
        return NO;
    }
#else
    return NO;
#endif
}

static NSArray *siteStateArray;
+ (NSArray *)getSiteState
{
    if (siteStateArray) {
        return siteStateArray;
    }
    
    siteStateArray = @[
        [NSNumber numberWithInt:TL_SiteStateBook],
    ];
    
    id state = [[NSUserDefaults standardUserDefaults] objectForKey:WX_SITE_STATE];
    if (!state) {
        return siteStateArray;
    }
    
    // 兼容老版站点选择
    if ([state isKindOfClass:[NSString class]]) {
        
        if ([state integerValue] != 0) {
            switch ([state integerValue]) {
                case 1:
                    siteStateArray = @[[NSNumber numberWithInt:TL_SiteStateBook]];
                    break;
                case 2:
                    siteStateArray = @[[NSNumber numberWithInt:TL_SiteStateComic]];
                    break;
                case 3:
                    siteStateArray = @[[NSNumber numberWithInt:TL_SiteStateBook], [NSNumber numberWithInt:TL_SiteStateComic]];
                    break;
                case 4:
                    siteStateArray = @[[NSNumber numberWithInt:TL_SiteStateComic], [NSNumber numberWithInt:TL_SiteStateBook]];
                    break;
                    
                default:
                    break;
            }
        }
        
    }
    
    // 新版站点选择
    if ([state isKindOfClass:[NSArray class]]) {
        NSMutableArray *t_siteArray = [NSMutableArray array];
        NSArray *t_arr = (NSArray *)state;
        for (NSString *siteString in t_arr) {
            if ([[TL_UtilsHelper formatStringWithObject:siteString] isEqualToString:@"1"]) {
                [t_siteArray addObject:[NSNumber numberWithInt:TL_SiteStateBook]];
            }
            
            if ([[TL_UtilsHelper formatStringWithObject:siteString] isEqualToString:@"2"]) {
                [t_siteArray addObject:[NSNumber numberWithInt:TL_SiteStateComic]];
            }
        }
        
        if (t_siteArray.count > 0) {
            siteStateArray = t_siteArray;
        }
    }
    
    return siteStateArray;
}

+ (BOOL)getAiReadSwitchState
{
    return NO;
}

+ (NSUInteger)getArcRandomNumWithMinNum:(NSUInteger)minNum maxNum:(NSUInteger)maxNum
{
    return arc4random() % ((maxNum + 1) - minNum) + minNum;
}

// 与当前的时间间隔
+ (NSInteger)getCurrentMinutesIntervalWithTimeStamp:(NSString *)timeStamp
{
    // 1.确定时间
    NSString *startTime = timeStamp;
    NSString *endTime = [self currentDateString];
    
    if (timeStamp) {
        NSDateFormatter *date = [[NSDateFormatter alloc] init];
        [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        NSDate *startdate = [date dateFromString:startTime];
        NSDate *enddate = [date dateFromString:endTime];
        
        //时间转时间戳的方法:
        NSTimeInterval aTime = [enddate timeIntervalSinceDate:startdate];
        
        return aTime / 60;
    } else {
        return -1;
    }
}

// 秒数转换成小时
+ (NSString *)getHourTimeTransformationWithTotalTimeLenght:(NSInteger)totalTimeLength
{
    NSInteger seconds = totalTimeLength;
    
    return [NSString stringWithFormat:@"%@:%@:%@",[NSString stringWithFormat:@"%02zd",(NSInteger)(seconds / 3600)], [NSString stringWithFormat:@"%02zd",(NSInteger)((seconds % 3600) / 60)], [NSString stringWithFormat:@"%02zd",(NSInteger)(seconds % 60)]];
}

// 秒数转换成分钟
+ (NSString *)getMinuteTimeTransformationWithTotalTimeLenght:(NSInteger)totalTimeLength
{
    NSInteger seconds = totalTimeLength;
    return [NSString stringWithFormat:@"%@:%@", [NSString stringWithFormat:@"%02zd", (NSInteger)((seconds % 3600) / 60)], [NSString stringWithFormat:@"%02zd", (NSInteger)(seconds % 60)]];
}

+ (NSString *)getTimeStamp
{
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}

+ (NSString *)formatStringWithObject:(id)object
{
    if ([object isKindOfClass:[NSString class]]) {
        return object;
    } else if (object) {
        return [NSString stringWithFormat:@"%@", object];
    } else {
        return @"";
    }
}

+ (NSString *)formatStringWithInteger:(NSUInteger)interger
{
    return [NSString stringWithFormat:@"%ld", interger];
}

+ (NSString *)formatStringWithFloat:(float)floatValue
{
    return [NSString stringWithFormat:@"%f", floatValue];
}

+ (NSUInteger)formatIntegerValueWithString:(NSString *)kstring
{
    return [[NSString stringWithFormat:@"%@",kstring] integerValue];
}

+ (NSString *)stringToMD5:(NSString *)inputStr
{
    const char *cStr = [inputStr UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr,(CC_LONG)strlen(cStr), result);
    NSString *resultStr = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                           result[0], result[1], result[2], result[3],
                           result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11],
                           result[12], result[13], result[14], result[15]
                           ];
    return [resultStr lowercaseString];
}

+ (NSString *)getTotalViews:(NSInteger)totalViews {
    if (totalViews >= 10000) {
        return [NSString stringWithFormat:@"%.2fw",(CGFloat)totalViews/10000];
    } else if (totalViews >= 1000) {
        return [NSString stringWithFormat:@"%.2fk",(CGFloat)totalViews/1000];
    } else {
        return [TL_UtilsHelper formatStringWithInteger:totalViews];
    }
}

+ (NSString *)getNotEmpty:(NSString *)originStr {
    return [originStr stringByReplacingOccurrencesOfString:@" " withString:@""];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if (err) {
        return nil;
    }
    return dic;
}

+ (NSString *)jsonStringWithDictionary:(NSDictionary *)dictionary
{
    if (!dictionary) {
        return @"";
    }
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
    }else{
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

+ (NSString *)convertFileSize:(int64_t)size
{
    if (size < 1024) { // B
        return [NSString stringWithFormat:@"%lldB", size];
    } else if (size >= 1024 && size < 1024 * 1024) { // KB
        return [NSString stringWithFormat:@"%.2fKB", (double)size / 1024];
    } else if(size >= 1024 * 1024 && size < 1024 * 1024 * 1024) { // MB
        return [NSString stringWithFormat:@"%.2fMB", (double)size / (1024 * 1024)];
    } else { // GB
        return [NSString stringWithFormat:@"%.2fGB", (double)size / (1024 * 1024 * 1024)];
    }
}

+ (NSString *)getRemainingMemorySpace
{
    // 剩余大小
    float freesize = 0.0;
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:nil];
    if (dictionary) {
        NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
        freesize = [_free unsignedLongLongValue] * 1.0;
    }
    return [self convertFileSize:freesize];
}

+ (NSString *)jsonStringWithObject:(id)object
{
    NSString *value = nil;
    if (!object) {
        return value;
    }
    if ([object isKindOfClass:[NSString class]]) {
        value = [TL_UtilsHelper jsonStringWithString:object];
    }else if([object isKindOfClass:[NSDictionary class]]) {
        value = [TL_UtilsHelper jsonStringWithDictionary:object];
    }else if([object isKindOfClass:[NSArray class]]) {
        value = [TL_UtilsHelper jsonStringWithArray:object];
    }
    return value;
}

+ (NSString *)jsonStringWithArray:(NSArray *)array
{
    NSMutableString *reString = [NSMutableString string];
    [reString appendString:@"["];
    NSMutableArray *values = [NSMutableArray array];
    for (id valueObj in array) {
        NSString *value = [TL_UtilsHelper jsonStringWithObject:valueObj];
        if (value) {
            [values addObject:[NSString stringWithFormat:@"%@",value]];
        }
    }
    [reString appendFormat:@"%@",[values componentsJoinedByString:@","]];
    [reString appendString:@"]"];
    return reString;
}

+ (NSString *)jsonStringWithString:(NSString *)string
{
    return [NSString stringWithFormat:@"\"%@\"",[[string stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"] stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""]];
}

+ (NSString *)currentDateString
{
    return [self currentDateStringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSString *)currentDateStringWithFormat:(NSString *)formatterStr
{
    // 获取系统当前时间
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = formatterStr;
    NSString *currentDateStr = [formatter stringFromDate:currentDate];
    
    return currentDateStr;
}

+ (NSString *)getCommentsMaxNumber:(NSInteger)commentsNum
{
    if (!commentsNum) {
        return @"0";
    }
    
    if (commentsNum > 99) {
        return @"99+";
    }
    
    return [self formatStringWithInteger:commentsNum];
}

+ (NSString *)dateStringWithTimestamp:(NSString *)timestamp {
    NSInteger currentTimestamp = [[self getTimeStamp] integerValue];
    
    if ([self isSameDay:[timestamp integerValue] Time2:currentTimestamp]) {
        // 小于60秒
        if (currentTimestamp - [timestamp integerValue] < 60) {
            return WXLocalizedString(@"刚刚");
        }
        
        // 小于60分钟
        if (currentTimestamp - [timestamp integerValue] < 3600) {
            NSInteger temp = (currentTimestamp - [timestamp integerValue]) / 60;
            return [NSString stringWithFormat:WXLocalizedString(@"%zd分钟前"), temp];
        }
        
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"hh:mm"];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp integerValue]];
        NSString *string = [dateFormat stringFromDate:date];
        return [NSString stringWithFormat:@"%@ %@", WXLocalizedString(@"今天"), string];
        
    } else {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm"];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp integerValue]];
        NSString *string = [dateFormat stringFromDate:date];
        return string;
    }
}

// 判断2个时间戳是不是同一天
+ (BOOL)isSameDay:(NSInteger)iTime1 Time2:(NSInteger)iTime2 {
    //传入时间毫秒数
    NSDate *pDate1 = [NSDate dateWithTimeIntervalSince1970:iTime1];
    NSDate *pDate2 = [NSDate dateWithTimeIntervalSince1970:iTime2];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:pDate1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:pDate2];
    
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}

+ (NSDictionary *)dicFromObject:(NSObject *)object {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int count;
    objc_property_t *propertyList = class_copyPropertyList([object class], &count);
 
    for (int i = 0; i < count; i++) {
        objc_property_t property = propertyList[i];
        const char *cName = property_getName(property);
        NSString *name = [NSString stringWithUTF8String:cName];
        NSObject *value = [object valueForKey:name];//valueForKey返回的数字和字符串都是对象
 
        if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]) {
            //string , bool, int ,NSinteger
            [dic setObject:value forKey:name];
 
        } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
            //字典或字典
            [dic setObject:[self arrayOrDicWithObject:(NSArray*)value] forKey:name];
 
        } else if (value == nil) {
            //null
            //[dic setObject:[NSNull null] forKey:name];//这行可以注释掉?????
         } else {
            //model
            [dic setObject:[self dicFromObject:value] forKey:name];
        }
    }
 
    return [dic copy];
}

/// 将可能存在model数组转化为普通数组
+ (id)arrayOrDicWithObject:(id)origin {
    if ([origin isKindOfClass:[NSArray class]]) {
        //数组
        NSMutableArray *array = [NSMutableArray array];
        for (NSObject *object in origin) {
            if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
                //string , bool, int ,NSinteger
                [array addObject:object];
 
            } else if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
                //数组或字典
                [array addObject:[self arrayOrDicWithObject:(NSArray *)object]];
 
            } else {
                //model
                [array addObject:[self dicFromObject:object]];
            }
        }
 
        return [array copy];
 
    } else if ([origin isKindOfClass:[NSDictionary class]]) {
        //字典
        NSDictionary *originDic = (NSDictionary *)origin;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (NSString *key in originDic.allKeys) {
            id object = [originDic objectForKey:key];
 
            if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
                //string , bool, int ,NSinteger
                [dic setObject:object forKey:key];
 
            } else if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
                //数组或字典
                [dic setObject:[self arrayOrDicWithObject:object] forKey:key];
 
            } else {
                //model
                [dic setObject:[self dicFromObject:object] forKey:key];
            }
        }
 
        return [dic copy];
    }
 
    return [NSNull null];
}

+ (nullable NSAttributedString *)rechargeAttributedStringFromAboutArray:(NSArray<NSString *> * _Nullable)about {
    if (kObjectIsEmpty(about)) return nil;
    return [NSAttributedString new];
    
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
//    
//    // 给富文本添加高亮文本和点击事件
//    void (^setTextHighlightBlock) (NSMutableAttributedString *, NSRange) = ^(NSMutableAttributedString *attr, NSRange range) {
//        if (!WXContainsRange(attr.rangeOfAll, range)) return;
//                
//        [attr setTextHighlightRange:range color:kMainColor backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
//            NSString *string = [text attributedSubstringFromRange:range].string;
//            
//            if ([string containsString:WXLocalizedString(@"意见反馈")]) {
////                [[TL_ViewHelper getWindowRootController] presentViewController:[[TL_NavigationController alloc] initWithRootViewController:[[TL_FeedbackSubViewController alloc] init]] animated:YES completion:nil];
//                return;
//            }
//            
//            TL_WebViewViewController *webViewController = [[TL_WebViewViewController alloc] init];
//            webViewController.isPresentState = NO;
//            
//            AppDelegate *delegate = (AppDelegate *)kRCodeSync([UIApplication sharedApplication].delegate);
//                        
//            if ([string containsString:WXLocalizedString(@"用户协议")]) {
//                webViewController.navTitle = WXLocalizedString(@"用户协议");
//                webViewController.URLString = [NSString stringWithFormat:@"%@",AgreementURL];
//                [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:webViewController animated:YES];
//                return;
//            }
//            
//            if ([string containsString:WXLocalizedString(@"隐私协议")]) {
//                webViewController.navTitle = WXLocalizedString(@"隐私协议");
//                webViewController.URLString = [NSString stringWithFormat:@"%@",PrivacyURL];
//                [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:webViewController animated:YES];
//                return;
//            }
//        }];
//    };
//    
//    NSArray *keywordArray = @[
//        @"用户协议", @"隐私协议", @"意见反馈"
//    ];
//    
//    NSArray *keywordArrayTranslation = @[
//        WXLocalizedString(@"用户协议"), WXLocalizedString(@"隐私协议"), WXLocalizedString(@"意见反馈")
//    ];
//    
//    for (NSString *obj in about) {
//        if (![obj isKindOfClass:NSString.class]) continue;
//        if (kObjectIsEmpty(obj)) continue;
//        
//        NSMutableString *t_string = [obj mutableCopy];
//        
//        // 如果末尾没有换行符则手动添加抑制符。
//        if (![t_string matchesRegex:@"[\r\n]$" options:kNilOptions]) {
//            [t_string appendString:@"\n"];
//        }
//        
//        // 消除###标记符
//        [t_string replaceOccurrencesOfString:@"###" withString:@"" options:kNilOptions range:t_string.rangeOfAll];
//        
//        // 翻译协议名称
//        for (int i = 0; i < keywordArray.count; i ++) {
//            NSString *keyword = [keywordArray wx_objectOrNilAtIndex:i];
//            BOOL isContainString = [t_string containsString:keyword];
//            if (!isContainString) continue;
//            
//            [t_string replaceOccurrencesOfString:keyword withString:[keywordArrayTranslation wx_objectOrNilAtIndex:i] options:kNilOptions range:t_string.rangeOfAll];
//        }
//        
//        NSMutableAttributedString *t_attr = [[NSMutableAttributedString alloc] initWithString:[t_string copy] attributes:@{NSFontAttributeName : kFont12, NSForegroundColorAttributeName : kGrayTextColor}];
//        
//        // 添加高亮和点击事件
//        for (int i = 0; i < keywordArrayTranslation.count; i ++) {
//            NSString *translateString = [keywordArrayTranslation wx_objectOrNilAtIndex:i];
//            NSRange range = [t_string rangeOfString:translateString];
//            if (range.location == NSNotFound) continue;
//            
//            // 创建包含左右符号的Range
//            NSRange moreRange = NSMakeRange(range.location - 1, range.length + 2);
//            
//            if (WXContainsRange(t_attr.rangeOfAll, moreRange)) {
//                setTextHighlightBlock(t_attr, moreRange);
//            } else {
//                setTextHighlightBlock(t_attr, range);
//            }
//        }
//        
//        [attributedString appendAttributedString:t_attr];
//    }
//    
//    attributedString.paragraphSpacing = kMoreHalfMargin;
//    attributedString.lineSpacing = kQuarterMargin;
//    
//    return [attributedString copy];
}

+ (NSString *)AESDecrypt:(NSString *)encryptText {
    NSArray *tmpArray = [encryptText componentsSeparatedByString:@","];
    if (tmpArray.count > 0) {
        NSString *tmpStr = tmpArray.firstObject;
        encryptText = [tmpStr stringByReplacingOccurrencesOfString:@"&ABCD&ABCD&" withString:@"/"];
    } else {
        return @"";
    }
    
    char keyPtr[kCCKeySizeAES128 + 1];
        memset(keyPtr, 0, sizeof(keyPtr));
    [kEncryptionKey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc] initWithBase64EncodedString:encryptText options:NSDataBase64DecodingIgnoreUnknownCharacters];//base64解码
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        
        NSString *tmpStr = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
        
        if (tmpStr.length == 0) {
            NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

            tmpStr = [[NSString alloc] initWithData:resultData encoding:enc];
        }
        tmpStr = [tmpStr stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
        tmpStr = [tmpStr stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];

        return tmpStr;
    }
    free(buffer);
    
    return nil;
}

+ (SEL)stringToSel:(NSString *)string {
    return NSSelectorFromString(string);
}

// 搜索历史
+ (void)saveSearchHistory:(NSArray *)list{
    [TLChacheUtils saveByKeyedArchiverWith:list fileName:kCGCache_searchHistory canClear:YES];
}

+ (NSArray *)getSearchHistory{
    NSArray *ary = [TLChacheUtils getByKeyedUnarchiver:kCGCache_searchHistory withClass:[NSArray class] canClear:YES];
    return ary;
}
+ (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString {
    if (!htmlString) return nil;
    
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];
    
    NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *options = @{
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, // 识别 HTML
        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
    };
    
    NSError *error = nil;
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithData:htmlData
                                                                          options:options
                                                               documentAttributes:nil
                                                                            error:&error];
    if (error) {
        NSLog(@"富文本解析失败: %@", error.localizedDescription);
        return [[NSAttributedString alloc] initWithString:@""]; // 返回空富文本兜底
    }
    
    // 统一设置默认字体（防止 HTML 未定义字体导致计算偏差）
    NSMutableAttributedString *mutableAttributedText = [attributedText mutableCopy];
    [mutableAttributedText addAttribute:NSFontAttributeName
                                  value:[UIFont systemFontOfSize:16.0]
                                  range:NSMakeRange(0, mutableAttributedText.length)];
    
    // 添加段落样式
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 4; // 行间距
    paragraphStyle.paragraphSpacing = 8; // 段落间距
    
    [mutableAttributedText addAttribute:NSParagraphStyleAttributeName
                                  value:paragraphStyle
                                  range:NSMakeRange(0, mutableAttributedText.length)];
    
    return [mutableAttributedText copy];
}

+ (NSDictionary *)mk_dictionaryWithUrlQuery:(NSString *)query{
    NSMutableDictionary *dic = @{}.mutableCopy;
    if (query){
        NSArray *paramAry = [query componentsSeparatedByString:@"&"];
        if (paramAry.count > 0) {
            for (NSString *param in paramAry) {
                NSArray *ary = [param componentsSeparatedByString:@"="];
                if (ary.count == 2) {
                    [dic setValue:ary[1] forKey:ary[0]];
                }
            }
        }
    }
    return dic.copy;
}

/** loading view */
static MBProgressHUD *s_hudView;
+ (void)showLoadingViewWith:(NSString *)message canCancel:(BOOL)cancel{
    mk_dispatch_async_on_main_queue(^{
        if ([UIApplication sharedApplication].keyWindow == nil){
            return;
        }
        if (!s_hudView) {
            s_hudView = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow
                                             animated:YES];
        }
        s_hudView.label.text = message;
        if (cancel) {
            UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                [TL_UtilsHelper hideLoadingView];
            }];
            [s_hudView addGestureRecognizer:tapGest];
        }
    });
}

+ (void)hideLoadingView{
    mk_dispatch_async_on_main_queue(^{
        if (s_hudView){
            [s_hudView hideAnimated:YES];
            s_hudView = nil;
        }
    });
}

+ (void)upReadingDurationWithWorksId:(NSNumber *)worksId andChaptertId:(NSNumber * _Nullable)chapterId andStartDate:(NSDate *)startDate{
    if (!TL_UserInfoManager.isLogin) {
        return;
    }
    if ((!worksId || !chapterId) && !startDate) {
        return;
    }
    
    if (!chapterId) {
        chapterId = @(0);
    }
    
    long long timestampInMilliseconds = (long long)([startDate timeIntervalSince1970]);
    
    NSTimeInterval difference = [[NSDate date] timeIntervalSinceDate:startDate];
    
    NSMutableDictionary *param = [@{
        @"worksId":worksId,
        @"chapterId":chapterId,
        @"userReadDate":[NSNumber numberWithLong:timestampInMilliseconds],
//        @"readTimes":[NSNumber numberWithLong:3000],
        @"readTimes":[NSNumber numberWithLong:difference],
    } mutableCopy];
    
    if (chapterId) {
        [param setObject:chapterId forKey:@"chapterId"];
    }
    
    [APIManager sendPostRequest:[APIURLManager bookRead] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            NSLog(@"上报成功");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
}

+ (void)guestAuthLoginAction:(void (^)(TL_UserInfoModel * _Nonnull))complete {
    
    NSMutableDictionary *param = [@{
        @"deviceId":[[NSUserDefaults standardUserDefaults] objectForKey:WX_IDFA_Code]
    } mutableCopy];
    
    [APIManager sendPostRequest:[APIURLManager guestAuthLogin] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];
            NSString *token = requestModel.data[@"token"];
            
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
            
            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            if (complete) {
                complete(usermodel);
            }
            
        }else{
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:error.localizedDescription];
    }];
    
    
}

@end
